package com.cction.activity.reinterest


import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment

import com.cction.R
import com.cction.adapter.DetailFragmentAdapter
import com.cction.comm.SaveCompoundUtils
import com.cction.entry.CctionBean
import com.cction.fragment.CctionDetailFragment
import com.umeng.analytics.MobclickAgent
import kotlinx.android.synthetic.main.cction_detail_main.*
import kotlinx.android.synthetic.main.title_bar.*

/**
 * 计算详情页
 */
class CCtionDetailActivity : AppCompatActivity(), View.OnClickListener {
    private val context = this
    private var cctionBean: CctionBean? = null

    private var pages: ArrayList<Fragment>? = null
    private var adapter: DetailFragmentAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.cction_detail_main)

        initView()
    }

    /**
     * 视图
     */
    private fun initView() {
        cctionBean = intent.getSerializableExtra("time") as CctionBean

        title_bar_other.text = "保存"
        val array = SaveCompoundUtils.readData(context).arrayList
        array?.forEach {
            if (it.id == cctionBean?.id) {
                title_bar_other.text = "记录"
            }
        }

        title_bar_title.text = "详情"

        title_bar_back.setOnClickListener(this)
        title_bar_other.setOnClickListener(this)

        pages = ArrayList()

        pages?.add(CctionDetailFragment.newInstance(cctionBean!!))

        adapter = DetailFragmentAdapter(supportFragmentManager, pages)
        ction_detail_viewpager.adapter = adapter
    }

    /**
     * 去详记录页
     */
    private fun toRecord() {
        val intent = Intent()
        intent.setClass(context, CompoundListActivity::class.java)
        startActivity(intent)
    }


    /**
     * 点击事件
     */
    override fun onClick(view: View) {
        when (view.id) {
            R.id.title_bar_back -> finish()
            R.id.title_bar_other -> {
                val value = title_bar_other.text.toString()
                if (value == "保存") {
                    title_bar_other.text = "记录"
                    SaveCompoundUtils.wirteData(context, cctionBean)
                    Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show()
                } else {
                    toRecord()
                }
            }
        }
    }

    public override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
    }

    public override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
    }
}
